<template>
  <div class="adddetail">
    <el-card shadow="hover">
      <el-form :model="formData" :rules="rules" ref="formData" label-width="100px">
        <el-form-item label="题目名称" prop="questionName">
          <el-input v-model="formData.questionName" placeholder="请输入题目名称"></el-input>
        </el-form-item>
        <el-form-item label="分数" prop="grade">
          <el-input-number v-model="formData.grade" :precision="2" :step="0.1" :max="1000000"></el-input-number>
        </el-form-item>
        <el-form-item label="分类" prop="types">
          <el-radio-group v-model="formData.types">
            <el-radio :label="0">单选</el-radio>
            <el-radio :label="1">多选</el-radio>
            <el-radio :label="2">判断</el-radio>
            <el-radio :label="3">填空</el-radio>
            <el-radio :label="4">主观题</el-radio>
            <el-radio :label="5">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <div v-if="formData.types === 0">
            <!-- 单选题 -->
            <el-radio-group v-model="formData.answer">
              <el-radio label="A">A</el-radio>
              <el-radio label="B">B</el-radio>
              <el-radio label="C">C</el-radio>
              <el-radio label="D">D</el-radio>
            </el-radio-group>
          </div>
          <div v-else-if="formData.types === 1">
            <!-- 多选题 -->
            <el-checkbox-group v-model="formData.answerArray" @change="updateAnswerString">
              <el-checkbox label="A">A</el-checkbox>
              <el-checkbox label="B">B</el-checkbox>
              <el-checkbox label="C">C</el-checkbox>
              <el-checkbox label="D">D</el-checkbox>
            </el-checkbox-group>
          </div>
          <div v-else-if="formData.types === 2">
            <!-- 判断题 -->
            <el-radio-group v-model="formData.answer">
              <el-radio label="√">√</el-radio>
              <el-radio label="×">×</el-radio>
            </el-radio-group>
          </div>
          <div v-else>
            <!-- 填空题、主观题、其他 -->
            <el-input v-model="formData.answer" placeholder="请输入答案"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="试题难度" prop="difficulty">
          <el-select
                v-model="formData.difficulty"
                clearable
                placeholder="试题难度"
            >
          <el-option
            v-for="option in difficultyOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="所属考试" prop="examId">
            <el-select
                v-model="formData.examName"
                disabled
                placeholder="所属考试"
            >
                <el-option
                :value="formData.examName"
                :label="formData.examName"
                ></el-option>
            </el-select>
        </el-form-item>
      </el-form>
      <div class="button-group">
        <el-button @click="goBack">返回</el-button>
        <el-button type="primary" @click="submitForm('formData')">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { insert, update, getExamDate } from '@/api/Questions/index';
import { get } from '@/api/Exam/index';
import { Message } from 'element-ui';

export default {
  data() {
    return {
      formData: {
        id: null, // 用于区分添加和修改
        questionName: '',
        answer: '',
        answerArray: [], // 多选题答案数组
        grade: null,
        types: null,
        examId: null,
        examName: '' // 新增字段用于存储考试名称
      },
      rules: {
        questionName: [
          { required: true, message: '请输入题目名称', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案', trigger: 'blur' },
          { validator: this.validateAnswer, trigger: 'blur' }
        ],
        grade: [
          { required: true, message: '请输入分数', trigger: 'blur' }
        ],
        types: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        difficulty:[
          {required: true, message: '请选择题目难度',trigger: 'change'}
        ],
        examId: [
          { required: true, message: '请选择所属考试', trigger: 'change' }
        ]
      },
      difficultyOptions: [
      { label: "容易", value: 0 },
      { label: "普通", value: 1 },
      { label: "困难", value: 2 },
      ],
      examIdOptions: [] // 考试选项
    };
  },
  methods: {
    // 更新多选题答案字符串
    updateAnswerString() {
      this.formData.answer = this.formData.answerArray.join('');
    },
    // 自定义答案验证
    validateAnswer(rule, value, callback) {
      if (this.formData.types === 1) {
        if (this.formData.answerArray.length === 0) {
          callback(new Error('请选择答案'));
        } else {
          callback();
        }
      } else {
        if (!value) {
          callback(new Error('请输入答案'));
        } else {
          callback();
        }
      }
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formData.types === 1) {
            // 多选题：将答案数组转换为字符串
            this.formData.answer = this.formData.answerArray.join('');
          }
          console.log("难度测试",this.formData);
          if (this.formData.id) {
            // 修改操作
            update(this.formData).then(() => {
              Message.success('修改成功');
              this.goBack();
            });
          } else {
            // 添加操作
            insert(this.formData).then(() => {
              Message.success('添加成功');
              location.reload(); // 强制刷新页面
              // this.goBack();
              // this.$router.push({ path: '/Questions/adddetail', query: { examId: this.formData.examId } }); // 跳转到当前页面
            });
          }
        }
      });
    },
    // 返回上一页
    goBack() {
      this.$router.back();
    }
  },
  mounted() {
    // 获取路由参数中的 examId
    const examId = this.$route.query.examId;
    console.log("获取到的 examId:", examId); // 打印 examId
    if (examId) {
      // 调用 get 方法获取考试详情
      get(examId).then((res) => {
        const examData = res.data; // 假设返回的数据中包含 examName
        this.formData.examName = examData.examName; // 绑定考试名称
        this.formData.examId = examId; // 保留 examId
      }).catch((error) => {
        console.error("获取考试信息失败:", error);
        this.$message.error("获取考试信息失败，请稍后重试");
      });
    }
    // 获取考试选项
    getExamDate().then((res) => {
      this.examIdOptions = res.data;
    });
    // 如果有 id 参数，加载试题数据
    const id = this.$route.query.id;
    if (id) {
      get(id).then((res) => {
        const data = res.data;
        if (data.types === 1) {
          // 多选题：将字符串转换为数组
          data.answerArray = data.answer.split('');
        } else {
          data.answerArray = [];
        }
        this.formData = { ...data };
      });
    }
  }
};
</script>

<style scoped>
.adddetail {
  padding: 20px;
}
.button-group {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>